﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace My
{
    [ParseChildren(typeof(MyView))]
    /// <summary>
    /// MyMultiView 的摘要描述
    /// </summary>
    public class MyMultiView : Control
    {
        public MyMultiView()
        {
            //
            // TODO: 在此加入建構函式的程式碼
            //
        }

        protected override void OnLoad(EventArgs e)
        {
            EnsureChildControls();
            base.OnLoad(e);            
        }

        protected override void CreateChildControls()
        {
            if (ActiveViewIndex == null)
            {
                return;
            }

            this.Controls.Clear();
            this.Controls.Add(Views[ActiveViewIndex.Value]);
        }

        protected override void AddParsedSubObject(object obj)
        {
            //this.Controls.Add(obj as MyView);
            
            if (obj is MyView)
            {
                Views.Add(obj as MyView);
            }
        }

        public int? ActiveViewIndex
        {
            get
            {
                return ViewState["ActiveViewIndex"] as int?;
            }
            set
            {
                ViewState["ActiveViewIndex"] = value;

                if (Views.Count == 0) // not loaded
                {
                    return;
                }

                this.Controls.Clear();
                this.Controls.Add(Views[value.Value]);

                if (SelectedIndexChanged != null)
                {
                    SelectedIndexChanged(this, EventArgs.Empty);
                }
                //this.Controls[ActiveViewIndex.Value].Controls.Clear();
                //(this.Controls[ActiveViewIndex.Value] as MyView).ContentTemplate.InstantiateIn(this.Controls[ActiveViewIndex.Value]);
            }
        }

        public void SetActiveView(MyView view)
        {
            this.ActiveViewIndex = Views.IndexOf(view);
        }

        public MyView GetActiveView()
        {
            return Views[ActiveViewIndex.Value];
        }

        List<MyView> Views = new List<MyView>();

        public event EventHandler SelectedIndexChanged;
    }

    [ParseChildren(false)]
    public class MyView : Control
    {
        ITemplate _template;

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate ContentTemplate
        {
            get
            {
                return _template;
            }
            set
            {
                _template = value;
            }
        }
    }
}